#include <crc16.h>
#include <stdio.h>
#include <jni.h>
#include <string.h>
#include <android/log.h>
#define DEBUG_TAG "NDK_HummingBirdCRC16"

unsigned int crc_update(unsigned short crc, unsigned char data){
  data ^= (crc & 0xff);
  data ^= data << 4;

  return ((((unsigned short)data << 8) | ((crc >> 8) & 0xff)) ^ (unsigned char)(data >> 4) ^ ((unsigned short)data << 3));
}

JNIEXPORT jint JNICALL Java_robotninja_driver_asctec_util_crc16_CRC16JniImp_crc16(JNIEnv *env, jobject obj, jintArray data_jni, jshort cnt_jni)
{
	jint* valuesjf = env->GetIntArrayElements(data_jni, 0);
	short cnt = (short) cnt_jni;

  	unsigned short crc=0xff;
  	unsigned int* ptr = reinterpret_cast<unsigned int*>(valuesjf);

	int i;
	for (i=0;i<cnt;i++){
		__android_log_print(ANDROID_LOG_VERBOSE, DEBUG_TAG, "PTR %i", ptr);
		crc=crc_update(crc, *ptr);
		ptr++;
	}

	env->ReleaseIntArrayElements(data_jni, valuesjf, 0);
	return crc;
}
